const path = require("path");
const { spawn } = require("child_process");
const { clipboard } = require("electron");

module.exports = {
  // 打开开发者工具
  openDevTools(win) {
    if (win) {
      win.webContents.openDevTools();
    }
  },
  openWebViewTools(win) {
    if (win) {
      // 打开webview开发者工具
      win.webContents.send("open-webview-devtools");
    }
  },
  // 刷新
  refreshWindow(win) {
    if (win) {
      win.reload();
    }
  },
  // 是否全屏
  toggleFullscreen(win) {
    if (win) {
      win?.setFullScreen(!win.isFullScreen());
    }
  },
  // 关闭应用
  closeApp(win) {
    if (win) {
      win.close();
    }
  },
  // 最小化应用
  minimizeWindow(win) {
    if (win) {
      win.minimize();
    }
  },
  // 恢复窗口
  restoreWindow(win) {
    if (win.isMinimized()) {
      win.restore(); // 如果窗口是最小化状态，则恢复
    } else {
      win.minimize();
      return;
    }
    win.focus(); // 聚焦窗口（即使已在任务栏）
  },
  // 注册截图快捷键
  execFileWay(isDevelopment, win, data) {
    // Windows 系统
    const url = this.getStaticPath(
      isDevelopment,
      "screenshot/ScreenCapture.exe"
    );
    const screen_window = spawn(url);
    screen_window.on("close", (code) => {
      if (code === 9) {
        // code 9表示保存到粘贴板操作
        this.clipboardParsing(win, data);
      } else if (data && data === "tool") { // 由聊天窗工具箱打开的
        win.webContents.send("to-webview-paste", "", data);
      }
    });
  },

  clipboardParsing(win, data) {
    // 1. 从剪贴板读取图片并转换为PNG格式
    const pngData = clipboard.readImage().toPNG();

    // 2. 转换为Base64（修正Buffer用法）
    const imgBase64 = Buffer.from(pngData).toString("base64");
    const imgSrc = `data:image/png;base64,${imgBase64}`;
    // 3. 发送截图文件
    win.webContents.send("to-webview-paste", imgSrc, data);
  },
  // 获取静态资源路径的辅助函数
  getStaticPath(isDevelopment, relativePath) {
    if (!isDevelopment) {
      // 生产环境：静态文件在resources目录下
      const staticPath = path.join(
        process.resourcesPath,
        "static",
        relativePath
      );
      console.log("Production static path:", staticPath);
      return staticPath;
    } else {
      // 开发环境：从utils目录回到项目根目录
      const staticPath = path.resolve(__dirname, "..", "static", relativePath);
      console.log("Development static path:", staticPath);
      return staticPath;
    }
  },
  // 获取应用内文件路径的辅助函数
  getAppPath(isDevelopment, relativePath) {
    if (!isDevelopment) {
      // 生产环境：app.asar在resources目录下
      return path.join(process.resourcesPath, "app.asar", relativePath);
    } else {
      // 开发环境：从utils目录回到项目根目录
      return path.resolve(__dirname, "..", relativePath);
    }
  },
  // 忽略缓存刷新webview
  refreshIgnoreCache(win) {
    if (win) {
      win.webContents.send("refresh-webview-ignorecache");
    }
  },
  // 打开/收起聊天室
  toggleChatroom(win) {
    if (win) {
      win.webContents.send("toggle-webview-chatroom");
    }
  },
};
